/**
 * 伯乐智能HR - 岗位选择界面
 * 实现岗位筛选、排序和选择功能
 */

const { createApp } = Vue;
const { ElMessage, ElMessageBox, ElNotification } = ElementPlus;

const app = createApp({
  data() {
    return {
      // 界面状态
      loading: true,
      isDark: false,
      
      // 数据状态
      jobList: [],
      filteredJobs: [],
      totalCandidates: 0,
      avgMatchRate: 85,
      
      // 筛选状态
      searchQuery: '',
      locationFilter: '',
      salaryFilter: '',
      sortBy: 'salary',
      
      // 系统状态
      systemStatus: {
        online: true,
        lastUpdate: null
      }
    };
  },
  
  computed: {
    // 获取唯一地点列表
    uniqueLocations() {
      const locations = this.jobList.map(job => job.location);
      return [...new Set(locations)].filter(loc => loc);
    }
  },
  
  async mounted() {
    try {
      await this.initializeSystem();
      await this.loadJobData();
    } catch (error) {
      console.error('初始化失败:', error);
      ElMessage.error('系统初始化失败，请刷新页面重试');
    }
  },
  
  methods: {
    // 系统初始化
    async initializeSystem() {
      try {
        // 设置主题
        if (localStorage.getItem('isDark') === 'true') {
          this.isDark = true;
          document.documentElement.setAttribute('data-theme', 'dark');
        }
        
        // 检查系统状态
        await this.checkSystemStatus();
        
        console.log('✅ 岗位选择系统初始化完成');
      } catch (error) {
        console.error('系统初始化失败:', error);
        this.systemStatus.online = false;
      }
    },
    
    // 检查系统状态
    async checkSystemStatus() {
      try {
        const response = await fetch('/api/hr/overview');
        const data = await response.json();
        
        this.systemStatus.online = data.success;
        this.systemStatus.lastUpdate = new Date().toISOString();
        
        if (data.success && data.data) {
          this.totalCandidates = data.data.totalCandidates || 0;
          this.avgMatchRate = Math.round(data.data.avgMatchScore || 85);
        }
      } catch (error) {
        this.systemStatus.online = false;
        console.warn('系统状态检查失败:', error);
      }
    },
    
    // 加载岗位数据
    async loadJobData() {
      this.loading = true;
      
      try {
        // 调用后端API获取岗位列表
        const response = await fetch('/api/hr/jobs');
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.success) {
          this.jobList = this.processJobData(result.jobs || []);
          this.filteredJobs = [...this.jobList];
          
          // 计算每个岗位的候选人数量
          await this.calculateCandidateCounts();
          
          // 应用默认排序
          this.sortJobs();
          
          ElMessage.success(`成功加载 ${this.jobList.length} 个岗位`);
        } else {
          throw new Error(result.message || '加载岗位数据失败');
        }
        
      } catch (error) {
        console.error('加载岗位数据失败:', error);
        ElMessage.error('加载岗位数据失败，请检查网络连接');
        
        // 使用模拟数据作为后备
        this.jobList = this.getMockJobData();
        this.filteredJobs = [...this.jobList];
        this.sortJobs();
        
      } finally {
        this.loading = false;
      }
    },
    
    // 处理岗位数据
    processJobData(rawJobs) {
      return rawJobs.map((job, index) => ({
        id: job.id || `job_${index}`,
        title: job.title || job.job_title || '未知职位',
        short_title: job.short_title || job.job_title_short || '',
        company_name: job.company_name || '未知公司',
        location: job.location || job.job_location || '未知地点',
        schedule_type: job.schedule_type || job.job_schedule_type || 'Full-time',
        work_from_home: Boolean(job.work_from_home || job.job_work_from_home),
        salary_year_avg: parseInt(job.salary_year_avg || 0),
        required_skills: this.parseSkillsArray(job.required_skills),
        preferred_skills: this.parseSkillsArray(job.preferred_skills),
        min_experience_years: parseInt(job.min_experience_years || 0),
        description: job.description || job.job_description || '暂无职位描述',
        candidateCount: 0 // 将被异步计算
      }));
    },
    
    // 解析技能数组
    parseSkillsArray(skillsData) {
      if (!skillsData) return [];
      
      if (Array.isArray(skillsData)) {
        return skillsData;
      }
      
      if (typeof skillsData === 'string') {
        try {
          // 尝试解析JSON格式
          if (skillsData.startsWith('[') && skillsData.endsWith(']')) {
            return JSON.parse(skillsData.replace(/'/g, '"'));
          }
          // 按逗号分割
          return skillsData.split(',').map(skill => skill.trim()).filter(skill => skill);
        } catch (error) {
          console.warn('解析技能数组失败:', skillsData, error);
          return [];
        }
      }
      
      return [];
    },
    
    // 计算候选人数量
    async calculateCandidateCounts() {
      for (const job of this.jobList) {
        try {
          // 模拟计算候选人匹配数量
          const mockCount = Math.floor(Math.random() * 50) + 10; // 10-60之间
          job.candidateCount = mockCount;
        } catch (error) {
          console.warn(`计算岗位 ${job.id} 候选人数量失败:`, error);
          job.candidateCount = '未知';
        }
      }
    },
    
    // 获取模拟岗位数据（用作后备）
    getMockJobData() {
      return [
        {
          id: 'job_001',
          title: 'Senior Software Engineer',
          company_name: 'Tech Corp',
          location: 'Beijing, China',
          schedule_type: 'Full-time',
          work_from_home: false,
          salary_year_avg: 350000,
          required_skills: ['Python', 'Java', 'SQL', 'Docker'],
          preferred_skills: ['Kubernetes', 'AWS', 'React'],
          min_experience_years: 5,
          description: '负责后端系统开发和维护，要求有丰富的微服务架构经验。',
          candidateCount: 45
        },
        {
          id: 'job_002',
          title: 'Data Scientist',
          company_name: 'AI Innovations',
          location: 'Shanghai, China',
          schedule_type: 'Full-time',
          work_from_home: true,
          salary_year_avg: 400000,
          required_skills: ['Python', 'Machine Learning', 'TensorFlow', 'Statistics'],
          preferred_skills: ['Deep Learning', 'PyTorch', 'Spark'],
          min_experience_years: 3,
          description: '负责机器学习模型开发，处理大规模数据分析任务。',
          candidateCount: 32
        },
        {
          id: 'job_003',
          title: 'Frontend Developer',
          company_name: 'Web Solutions',
          location: 'Shenzhen, China',
          schedule_type: 'Full-time',
          work_from_home: false,
          salary_year_avg: 280000,
          required_skills: ['React', 'JavaScript', 'TypeScript', 'CSS'],
          preferred_skills: ['Vue.js', 'Node.js', 'GraphQL'],
          min_experience_years: 2,
          description: '负责前端用户界面开发，要求熟悉现代前端框架。',
          candidateCount: 28
        }
      ];
    },
    
    // 筛选岗位
    filterJobs() {
      let filtered = [...this.jobList];
      
      // 搜索筛选
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.toLowerCase().trim();
        filtered = filtered.filter(job => {
          const searchFields = [
            job.title,
            job.company_name,
            job.description,
            ...(job.required_skills || []),
            ...(job.preferred_skills || [])
          ];
          
          return searchFields.some(field => 
            field && field.toString().toLowerCase().includes(query)
          );
        });
      }
      
      // 地点筛选
      if (this.locationFilter) {
        filtered = filtered.filter(job => 
          job.location && job.location.includes(this.locationFilter)
        );
      }
      
      // 薪资筛选
      if (this.salaryFilter) {
        filtered = filtered.filter(job => {
          const salary = job.salary_year_avg || 0;
          switch (this.salaryFilter) {
            case 'low':
              return salary < 200000;
            case 'medium':
              return salary >= 200000 && salary <= 300000;
            case 'high':
              return salary > 300000;
            default:
              return true;
          }
        });
      }
      
      this.filteredJobs = filtered;
    },
    
    // 排序岗位
    sortJobs() {
      this.filteredJobs.sort((a, b) => {
        switch (this.sortBy) {
          case 'salary':
            return (b.salary_year_avg || 0) - (a.salary_year_avg || 0);
          case 'company':
            return (a.company_name || '').localeCompare(b.company_name || '');
          case 'title':
            return (a.title || '').localeCompare(b.title || '');
          default:
            return 0;
        }
      });
    },
    
    // 重置筛选条件
    resetFilters() {
      this.searchQuery = '';
      this.locationFilter = '';
      this.salaryFilter = '';
      this.sortBy = 'salary';
      this.filteredJobs = [...this.jobList];
      this.sortJobs();
      ElMessage.success('筛选条件已重置');
    },
    
    // 选择岗位
    async selectJob(job) {
      try {
        // 保存选中的岗位到localStorage
        localStorage.setItem('selectedJob', JSON.stringify(job));
        
        // 显示确认信息
        ElNotification({
          title: '岗位已选择',
          message: `您选择了「${job.title}」岗位，即将进入候选人筛选界面`,
          type: 'success',
          duration: 3000
        });
        
        // 跳转到Living Workspace界面
        setTimeout(() => {
          window.location.href = '/living_workspace.html';
        }, 1000);
        
      } catch (error) {
        console.error('选择岗位失败:', error);
        ElMessage.error('选择岗位失败，请重试');
      }
    },
    
    // 刷新岗位
    async refreshJobs() {
      await this.loadJobData();
      ElMessage.success('岗位数据已刷新');
    },
    
    // 切换主题
    toggleTheme() {
      this.isDark = !this.isDark;
      document.documentElement.setAttribute('data-theme', this.isDark ? 'dark' : 'light');
      localStorage.setItem('isDark', this.isDark.toString());
      
      ElMessage.success(`已切换到${this.isDark ? '暗色' : '亮色'}主题`);
    },
    
    // 格式化薪资显示
    formatSalary(salary) {
      if (!salary || salary === 0) {
        return '薪资面议';
      }
      
      if (salary >= 10000) {
        const wan = Math.round(salary / 10000);
        return `${wan}万/年`;
      }
      
      return `${salary}元/年`;
    },
    
    // 格式化时间显示
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const now = new Date();
      const diffMs = now - date;
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMs / 3600000);
      
      if (diffMins < 1) return '刚刚';
      if (diffMins < 60) return `${diffMins}分钟前`;
      if (diffHours < 24) return `${diffHours}小时前`;
      
      return date.toLocaleDateString('zh-CN');
    }
  },
  
  // 监听器
  watch: {
    searchQuery() {
      this.filterJobs();
    },
    
    sortBy() {
      this.sortJobs();
    }
  }
});

// 使用Element Plus
app.use(ElementPlus);

// 全局配置
app.config.globalProperties.$message = ElMessage;
app.config.globalProperties.$messageBox = ElMessageBox;
app.config.globalProperties.$notify = ElNotification;

// 挂载应用
app.mount('#app');

// 全局错误处理
window.addEventListener('unhandledrejection', (event) => {
  console.error('未处理的Promise拒绝:', event.reason);
  ElMessage.error('系统错误，请刷新页面重试');
});

console.log('🚀 伯乐智能HR 岗位选择界面已启动');
















